package com.hermes.comics.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;

import com.hermes.comics.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import java.net.HttpURLConnection;
import java.net.URL;

import java.util.ArrayList;
import java.util.List;

/**
 * http://www.vogella.com/articles/AndroidNetworking/article.html
 * http://www.tbray.org/ongoing/When/201x/2012/01/17/HttpURLConnection
 */
public class RemoteCatalogDialog extends ProgressDialog {

  private static final String USER_AGENT =
      "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36";
   
  public interface Interface {
    public String getUrl();
    public void onPreExecute();
    public void onCancelled();
    public void onSuccess(UrlWrapper result);
    public void onFailure(UrlWrapper result);
  }

  private final Activity activity;
  private AsyncCatalog asyncCatalog;

  protected RemoteCatalogDialog(Activity activity) {
    super(activity);
    this.activity = activity;

    setMessage(activity.getString(R.string.please_wait, ""));
    setCancelable(false);
    setIndeterminate(true);
    setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
          abort();
        }
      });
  }

  protected void abort() {
    asyncCatalog.cancel(true);
  }

  protected Activity getActivity() {
    return activity;
  }

  protected void execute(Interface dialogInterface) {
    asyncCatalog = new AsyncCatalog(dialogInterface);
    asyncCatalog.execute(dialogInterface.getUrl());
  }

  class AsyncCatalog extends AsyncTask<String, UrlWrapper, UrlWrapper> {

    private final Interface dialogInterface;

    public AsyncCatalog(Interface dialogInterface) {
      this.dialogInterface = dialogInterface;
    }

    @Override
    public void onPreExecute() {
      dialogInterface.onPreExecute();
    }

    @Override
    public void onCancelled(UrlWrapper result) {
      dialogInterface.onCancelled();
    }

    @Override
    public void onPostExecute(UrlWrapper result) {
      if (result.httpStatus() == HttpURLConnection.HTTP_OK) {
        dialogInterface.onSuccess(result);
      } else {
        dialogInterface.onFailure(result);
      }
    }

    @Override
    protected UrlWrapper doInBackground(String... urls) {
      UrlWrapper result = new UrlWrapper(urls[0]).fetch();
      publishProgress(result);
      return result;
    }
  }

  static class UrlWrapper {
    private final String url;
    private StringBuffer content;
    private int httpStatus;
    private String message;

    public UrlWrapper(String url) {
      this.url = url;
      this.content = new StringBuffer();
      this.httpStatus = HttpURLConnection.HTTP_SEE_OTHER;
      this.message = "";
    }

    public UrlWrapper fetch() {
      BufferedReader reader = null;
      try {
        URL urlHandler = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlHandler.openConnection();
        conn.setRequestProperty("User-Agent", USER_AGENT);
        conn.setInstanceFollowRedirects(true);

        System.out.println("----------> " + url);

        reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        httpStatus = conn.getResponseCode();

        if (httpStatus != HttpURLConnection.HTTP_OK) {
          message = conn.getResponseMessage() + " - " + conn.getHeaderField("Location");
          return this;
        }

        String line = "";
        while ((line = reader.readLine()) != null) {
          content.append(line + "\n");
        }

      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        if (reader != null) {
          try {
            reader.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      return this;
    }

    public String message() {
      return message;
    }

    public String content() {
      return content.toString();
    }

    public int httpStatus() {
      return httpStatus;
    }

    public String url() {
      return url;
    }
  }
}
